<script setup>
import { computed, reactive, ref } from "vue";
import { useRoute } from "vue-router";
import request from "../utils/request";
import { useCartStore, useShopStore } from "@/stores";
import router from "@/router";
const onClickLeft = () => history.back();
const userId = localStorage.getItem("userId");
const route = useRoute();
const dafaultAdr = ref({});
const orderList = ref([]);
const showJump = ref(true);
const cartStore = useCartStore();
const shopStore = useShopStore();
const { shops } = shopStore;
const { cartList } = cartStore;
const productsData = cartList[route.params.shopId];
// 获得传过来的店铺id的商品列表

// 从订单跳转
if (route.params.data) {
  // 订单详情
  showJump.value = false;
  // 商品
  orderList.value = JSON.parse(JSON.parse(route.params.data).products);
  // 地址
  const getOrderAdr = async (code) => {
    const result = await request.get("/api/v1/address/" + userId);
    result.data.forEach((element) => {
      if (element.id === code) {
        dafaultAdr.value = element;
      }
    });
  };
  getOrderAdr(JSON.parse(route.params.data).address_id);
} else {
  // 从提交订单跳转
  // 订单结算
  showJump.value = true;
  // 遍历购物车列表，把当前店铺id的商品放到订单列表中
  for (const key in productsData) {
    if (Object.prototype.hasOwnProperty.call(productsData, key)) {
      const element = productsData[key];
      orderList.value.push(element);
    }
  }
  // 默认地址
  const getDefaultAdr = async () => {
    const result = await request.get("/api/v1/defaultAddress/" + userId);
    dafaultAdr.value = result.data;
  };
  getDefaultAdr();
}
let products = [];
// 遍历订单列表，把id，数量，总计和商品信息放到一个空数组里
const submitOrder = async () => {
  for (let i in orderList.value) {
    const product = orderList.value[i];
    products.push({ id: parseInt(product.id, 10), num: product.count });
  }
  // 发送创建订单的请求
  const result = await request.post("/api/v1/create", {
    id: userId,
    addressId: dafaultAdr.value.id,
    shopId: route.params.shopId,
    shopName: shops[route.params.shopId],
    products: JSON.stringify(products),
  });
  router.push("/orders");
  // 跳转到订单页并清楚购物车
  cartStore.clearCart(route.params.shopId);
};
let amount = computed(() => {
  return orderList.value.reduce((total, item) => {
    return (total += item.count * item.price);
  }, 0);
});

const showAdr = ref(false);
const OptionAdr = () => (showAdr.value = true);
const onClickleft = () => (showAdr.value = false);
const add = () => (showAdr.value = false);
const chosenAddressId = ref("1");
const listData = ref([]);
// 获取所有地址
const getAdr = async () => {
  const list = await request.get("/api/v1/address/" + userId);
  // 遍历所有地址，把每一个地址都添加到listData中：element是每一项地址
  list.data.forEach((element) => {
    listData.value.push({
      id: element.id,
      name: element.real_name,
      tel: element.mobile,
      address: element.city + element.house,
      data: element,
      isDefault: element.is_default ? true : false, //判断默认地址
    });
  });
};
getAdr();

const select = (item) =>{
  dafaultAdr.value = item.data  
}
</script>

<template>
  <template v-if="showAdr">
    <van-nav-bar
      title="选择收货地址"
      left-text="返回"
      left-arrow
      @click-left="onClickleft"
    />
    <div>
      <van-address-list
        v-model="chosenAddressId"
        :list="listData"
        switchable
        default-tag-text="默认"
        add-button-text="保存此选择"
        @select="select"
        @add="add"
      />
    </div>
  </template>
  <template v-else="showAdr">
    <div class="confirm-back">
      <div class="top-nav">
        <van-icon
          class="custom-icon"
          name="arrow-left"
          size="22"
          @click="onClickLeft"
        />
        <p v-if="showJump">确认订单</p>
        <p v-else>查看订单</p>
      </div>
      <div class="address" @click="OptionAdr">
        <p>收货地址</p>
        <p>{{ dafaultAdr.city }}{{ dafaultAdr.house }}</p>
        <p>{{ dafaultAdr.real_name }} {{ dafaultAdr.mobile }}</p>
      </div>
      <div class="shop-card">
        <p v-if="showJump">{{ shops[route.params.shopId] }}</p>
        <p v-else>{{ JSON.parse(route.params.data).shop_name }}</p>
        <ul>
          <li v-for="item in orderList" :key="item.id" class="goods-list">
            <img :src="item.img_url" alt="" />
            <div class="info">
              <p>{{ item.name }}</p>
              <span> ¥{{ item.price }} × {{ item.count }}</span>
            </div>
            <div class="total">¥{{ item.price * item.count }}</div>
          </li>
        </ul>
      </div>
      <van-submit-bar>
        <template #default>
          <p class="amount">
            实付金额: <span> ¥{{ amount }}</span>
          </p>
        </template>
        <template #button>
          <button v-if="showJump" class="submit" @click="submitOrder">
            提交订单
          </button>
        </template>
      </van-submit-bar>
    </div>
  </template>
</template>
<style scoped lang="scss">
.confirm-back {
  position: relative;
  width: 100%;
  height: 100vh;
  background: linear-gradient(to bottom, #7543e0 132px, #f8f8f8 132px);
  .top-nav {
    height: 46px;
    position: relative;
    .custom-icon {
      position: absolute;
      top: 12px;
      left: 10px;
      color: white;
    }
    p {
      text-align: center;
      color: #fff;
      height: 46px;
      line-height: 46px;
      font-size: 16px;
      font-weight: 500;
    }
  }
}
.address {
  width: 92%;
  margin: 10px auto;
  padding: 16px 20px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 0 3px #82828231;
  p:first-child {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 10px;
  }
  p:nth-child(2) {
    font-size: 14px;
  }
  p:nth-child(3) {
    font-size: 12px;
  }
}
.shop-card {
  position: relative;
  width: 92%;
  margin: 10px auto;
  padding: 16px 20px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 0 3px #82828231;
  .orderId {
    position: absolute;
    right: 10px;
    top: 18px;
    font-size: 12px;
  }
  & > p {
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 10px;
  }
  .goods-list {
    display: flex;
    justify-content: space-between;
    margin-bottom: 14px;
    img {
      width: 38px;
      height: 38px;
    }
    .info {
      padding-left: 16px;
      text-align: left;
      flex-grow: 1;
      p {
        font-weight: 600;
      }
      span {
        color: rgb(254, 57, 57);
      }
    }
    .total {
      height: 38px;
      padding-top: 23px;
    }
  }
}
.amount {
  width: 100%;
  text-align: left;
  font-weight: 600;
  span {
    font-size: 18px;
  }
}
.submit {
  position: absolute;
  right: 0;
  top: 0;
  background-color: #7543e0;
  border: none;
  width: 100px;
  height: 48px;
  color: #fff;
}
</style>
